package com.example.advice;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@ControllerAdvice
public class GlobalBinderAdvice {

    public static class LocalDateTimePropertyEditor extends PropertyEditorSupport {

        private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        @Override
        public String getAsText() {
            LocalDateTime localDateTime = (LocalDateTime) getValue();
            return formatter.format(localDateTime);
        }

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            LocalDateTime localDateTime = LocalDateTime.parse(text, formatter);
            setValue(localDateTime);
        }
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDateTime.class, new LocalDateTimePropertyEditor());
    }
}
